
package io.wmy.supex.framework.support.log4j;

import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.apache.logging.log4j.core.pattern.*;

import java.util.List;

@Plugin(name = "appendSpace", category = PatternConverter.CATEGORY)
@ConverterKeys({ "sp", "appendSpace" })
public final class AppendSpaceConverter extends LogEventPatternConverter {

    private final List<PatternFormatter> patternFormatters;

    private AppendSpaceConverter(final List<PatternFormatter> patternFormatters) {
        super("appendSpace", "appendSpace");
        this.patternFormatters = patternFormatters;
    }

    public static AppendSpaceConverter newInstance(final Configuration config, final String[] options) {
        if (options.length != 1) {
            LOGGER.error("Incorrect number of options on appendSpace. Expected 1 received " + options.length);
            return null;
        }
        if (options[0] == null) {
            LOGGER.error("No pattern supplied on appendSpace");
            return null;
        }
        final PatternParser parser = PatternLayout.createPatternParser(config);
        final List<PatternFormatter> formatters = parser.parse(options[0]);
        return new AppendSpaceConverter(formatters);
    }

    @Override
    public void format(final LogEvent event, final StringBuilder toAppendTo) {
        final StringBuilder buf = new StringBuilder();
        for (final PatternFormatter formatter : patternFormatters) {
            formatter.format(event, buf);
        }
        toAppendTo.append(buf.toString());
        if (buf.length() > 0) {
            toAppendTo.append(" ");
        }
    }
}

